package cn.com.sbell.vss.monitor.getter;

public class LinuxPerformanceDataGetter extends AbstractPerformanceDataGetter {

	public int getCpuUsage() {
		try {
			String command = "vmstat 1 2";
			String result = executeCommand(command);
			String row = getRow(result, -1);
			int count=getIndex(getRow(result,2),"id");
			
//			suse uses -3, not -2
			String col = getColumn(row, count);
			return 100 - Integer.parseInt(col);
		} catch (Throwable ex) {
			return -1;
		}
	}

	public int getDiskUsage(String mountedPath) {
		try {
			if (mountedPath == null || "".equals(mountedPath)) {
				mountedPath = "/";
			}
			String command = "df";
			String result = executeCommand(command);
			int rc = getRowCount(result);
			for (int i = 2; i <= rc; i++) {
				String row = getRow(result, i);
				if (mountedPath.equals(getColumn(row, -1))) {
					String s = getColumn(row, -2);
					if (s.endsWith("%")) {
						s = s.substring(0, s.length() - 1);
					}
					return Integer.parseInt(s);
				}
			}
		} catch (Throwable ex) {
			return -1;
		}
		return -1;
	}

	public int getMemoryUsage() {
		try {
			String command = "head -n 2 /proc/meminfo";
			String result = executeCommand(command);
			String tm = getRow(result, 1);
			String fm = getRow(result, 2);
			String t = getColumn(tm, -2);
			String f = getColumn(fm, -2);
			return 100 - (Integer.parseInt(f) * 100 / Integer.parseInt(t));
		} catch (Throwable ex) {
			return -1;
		}
	}

}
